import re
from contextlib import asynccontextmanager
from fastapi import FastAPI, Request, Form, Depends
from fastapi.templating import Jinja2Templates
from fastapi.responses import HTMLResponse
import uvicorn
from sqlmodel import Session
from starlette.staticfiles import StaticFiles
from processing import download_bilibili
from sql_app import curd
from sql_app.database import init_db, get_session



@asynccontextmanager
async def lifespan(app: FastAPI):
    # 启动时执行
    init_db()
    yield

app = FastAPI(lifespan=lifespan)



# 挂载静态文件目录
app.mount("/b_videos", StaticFiles(directory="static/b_videos"), name="b_videos")
templates = Jinja2Templates(directory="templates")


@app.get("/", response_class=HTMLResponse)
async def read_root(request: Request, db: Session = Depends(get_session)):
    return templates.TemplateResponse("index.html", {"request": request})


@app.post("/download", response_class=HTMLResponse)
async def video_download(request: Request, video_url: str = Form(...), db: Session = Depends(get_session)):
    try:
        # 在video_download接口中添加
        if not re.match(r'^https?://(www\.)?bilibili\.com/video/', video_url):
            return {"status": "error", "message": "请输入有效的B站视频链接"}

        # 下载代码
        title, file_name, file_uuid = await download_bilibili.Get_B_video(url=video_url)
        curd.create_download_info(db=db,title=title,video_url=video_url,file_name=file_name)
        return templates.TemplateResponse("index.html", {"request": request, "status": "success", "message": "下载成功", "file_uuid": file_uuid})

    except Exception as e:
            # 即使出错，也返回页面，避免白屏
            return templates.TemplateResponse(
                "index.html",
                {
                    "request": request,
                    "status": "error",
                    "message": f"下载失败: {str(e)}",
                }
            )
if __name__ == '__main__':
    # 启动FastAPI应用
    uvicorn.run(app="main:app", host='0.0.0.0', port=8002, reload=True)  # 在指定端口和主机上启动应用
